﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;

namespace StatusPlan3.UC
{
    /// <summary>
    /// Interaction logic for UCTask.xaml
    /// </summary>
    public partial class UCTask : UserControl
    {
        public Task task;
        public Project project;
        public ProjectGroup projectGroup;
        public Subproject subproject;
        public RadPane rp;
        Boolean isNew = false;


        public UCTask()
        {
            InitializeComponent();
        }

        public void setData(Task t, Project p, ProjectGroup pg, Subproject sp = null)
        {
            task = t;
            project = p;
            projectGroup = pg;
            subproject = sp;
            polulateFrame();
        }

        public void showNew(Project p, ProjectGroup pg, Subproject sp = null)
        {
            project = p;
            projectGroup = pg;
            subproject = sp;
            isNew = true;
            task = new Task();
            task.createdBy = StatusPlanData.currentUser;
            task.createdDate = DateTime.Now;
            TextBlock_TaskName.Text = "Stovna verkætlan";
            TextBlock_CreatedBy.Text = " ";
            TextBlock_CreatedDate.Text = " ";
            TextBlock_ProjectGroupName.Text = " -Bólkur: " + projectGroup.name + " / " + project.name;
            saveButton.Content = "Stovna";
            saveButton.Visibility = System.Windows.Visibility.Visible;
            cancelButton.Visibility = System.Windows.Visibility.Collapsed;
            Message_Tab.Visibility = System.Windows.Visibility.Collapsed;
            LogTab.Visibility = System.Windows.Visibility.Collapsed;
            SubprojectsTab.Visibility = System.Windows.Visibility.Collapsed;
            ShowFilesButton.Visibility = System.Windows.Visibility.Collapsed;
            TextBox_TimeUsed.IsEnabled = false;
            RadDatePicker_EndDate.IsEnabled = false;
            TextBox_ID.IsEnabled = false;
            polulateFrame();
        }

        public void refreshFrame()
        {
            polulateFrame();
        }

        public void polulateFrame()
        {
            if(!isNew)
                task = StatusPlanData.statusPlanHandler.getTask(task.id);

            TextBlock_TaskName.Text = task.name;
            
            if(task.responsible != null)
                TextBlock_Responsible.Text = " -Ábyrgd: " + task.responsible.fullName;

            TextBlock_CreatedBy.Text = " -Stovnað: " + task.createdBy.fullName;
            TextBlock_CreatedDate.Text = " -Stovnað: " + task.createdDate.ToString("dd-MM-yyyy HH:mm");
            TextBlock_ProjectGroupName.Text = " -Bólkur: " + projectGroup.name + " / " + project.name;
            if (task.subprojectName != null)
                TextBlock_ProjectGroupName.Text += " / " + task.subprojectName;

            if(task.messages.Count > 0)
                Message_Tab.Header = "Boð (" + task.messages.Count + ")";

            //LOAD TASK DATA
            TextBox_name.Text = task.name;

            TextBox_ID.Text = task.id + "";
            TextBox_ID.IsEnabled = false;

            ComboBox_Priority.ItemsSource = projectGroup.priorities;
            ComboBox_Priority.DisplayMemberPath = "name";
            
            foreach (var type in projectGroup.priorities)
                if (task.priority != null && type.id == task.priority.id) ComboBox_Priority.SelectedItem = type;

            ComboBox_Type.ItemsSource = projectGroup.types;
            ComboBox_Type.DisplayMemberPath = "name";
            
            foreach (var type in projectGroup.types)
                if (task.type != null && type.id == task.type.id) ComboBox_Type.SelectedItem = type;

            ComboBox_Responsible.ItemsSource = projectGroup.projectMembers;
            ComboBox_Responsible.DisplayMemberPath = "fullName";
            
            foreach (var type in projectGroup.projectMembers)
                if (task.responsible != null && type.id == task.responsible.id) ComboBox_Responsible.SelectedItem = type;

            RadDatePicker_StartDate.SelectedDate = task.startedDate;
            RadDatePicker_EndDate.SelectedDate = task.endDate;          
            TRadDatePicker_EstimatedEnd.SelectedDate = task.plannedEndDate;
            TextBox_EstimatedHours.Text = task.estimatedTime + "";
            

            TextBox_TimeUsed.Text = task.timeUsed + "";
            

            RadDatePicker_Deadline.SelectedDate = task.deadline;


            Tasks pTasks = new Tasks();
            if (subproject == null)
                pTasks = project.tasks;
            else
                pTasks = subproject.tasks;

            ComboBox_Parent.ItemsSource = pTasks;
            ComboBox_Parent.DisplayMemberPath = "name";

            foreach (Task type in pTasks)
                if (task.parent != null && type.id == task.parent.id) ComboBox_Responsible.SelectedItem = type;

            Subprojects sp = StatusPlanData.statusPlanHandler.getSubprojects(project.id);
            ComboBox_Subproject.ItemsSource = sp;
            ComboBox_Subproject.DisplayMemberPath = "name";
            foreach (var type in sp)
                if (subproject != null && type.id == subproject.id) ComboBox_Responsible.SelectedItem = type;

            descriptionTextBox.Text = task.description;

            TextBox_name.TextChanged += new TextChangedEventHandler(TextBox_EstimatedHours_TextChanged);
            ComboBox_Priority.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            ComboBox_Type.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            ComboBox_Responsible.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            RadDatePicker_StartDate.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            RadDatePicker_EndDate.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            TRadDatePicker_EstimatedEnd.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            TextBox_EstimatedHours.TextChanged += new TextChangedEventHandler(TextBox_EstimatedHours_TextChanged);
            TextBox_TimeUsed.TextChanged += new TextChangedEventHandler(TextBox_EstimatedHours_TextChanged);
            RadDatePicker_Deadline.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            ComboBox_Parent.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            ComboBox_Subproject.SelectionChanged += new SelectionChangedEventHandler(Inuput_SelectionChanged);
            descriptionTextBox.TextChanged += new TextChangedEventHandler(TextBox_EstimatedHours_TextChanged);

            if (!isNew)
            {
                SaveChanges_StackPanel.Visibility = System.Windows.Visibility.Collapsed;

                if (task.estimatedTime != null && task.timeUsed != null)
                {
                    Decimal time = task.estimatedTime.Value;
                    Decimal usedTime = task.timeUsed.Value;

                    if (task.addedEstimatedHours != null)
                        time += task.addedEstimatedHours.Value;

                
                    Decimal progress = usedTime/time * 100;
                    if (progress <= 100)
                    {
                        RadProgressBar_Progress.Value = (double)progress;
                    
                    }
                    else
                    {
                        RadProgressBar_Progress.Foreground = new SolidColorBrush(Colors.Red);
                        RadProgressBar_Progress.Value = 100;

                    }
                }

            
                //LoadSubTasks
                if (task.decendants.Count > 0)
                {
                    SubprojectsTab.Visibility = System.Windows.Visibility.Visible;
                    taskGridView.ItemsSource = task.decendants;
                }

                //Load Messages;
                UC.UCMessages ucMessages = new UC.UCMessages(task.messages);
                ucMessages.task = this;
                MessageGroupBox.Content = ucMessages;

                //Load Files
                UC.UCFiles ucFiles = new UCFiles(task.attachedFiles);
                FileGroupBox.Content = ucFiles;
                ucFiles.ucTask = this;
            }
        }

        void TextBox_EstimatedHours_TextChanged(object sender, TextChangedEventArgs e)
        {
            SaveChanges_StackPanel.Visibility = System.Windows.Visibility.Visible;
        }

        void Inuput_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SaveChanges_StackPanel.Visibility = System.Windows.Visibility.Visible;
        }

        private void RadButton_Click(object sender, RoutedEventArgs e)
        {
            if (FileGroupBox.Visibility == System.Windows.Visibility.Collapsed)
            {
                Splitter.Visibility = System.Windows.Visibility.Visible;
                FileGroupBox.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                Splitter.Visibility = System.Windows.Visibility.Collapsed;
                FileGroupBox.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void RadButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (MessageGroupBox.Visibility == System.Windows.Visibility.Collapsed)
                MessageGroupBox.Visibility = System.Windows.Visibility.Visible;
            else
                MessageGroupBox.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void RadButton_Click_2(object sender, RoutedEventArgs e)
        {
            if (LogGroupBox.Visibility == System.Windows.Visibility.Collapsed)
                LogGroupBox.Visibility = System.Windows.Visibility.Visible;
            else
                LogGroupBox.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void Splitter_MouseEnter(object sender, MouseEventArgs e)
        {
            Splitter.Background = new SolidColorBrush(Colors.LightBlue);
        }

        private void Splitter_MouseLeave(object sender, MouseEventArgs e)
        {
            Splitter.Background = new SolidColorBrush(Colors.Transparent);
        }

        private void RadButton_Click_3(object sender, RoutedEventArgs e)
        {
            refreshFrame();
        }

        public Boolean validateFields()
        {
            Boolean ok = true;


            return ok;
        }

        private void RadButton_Click_4(object sender, RoutedEventArgs e)
        {
            
            if (validateFields())
            {
                Priority priority = ComboBox_Priority.SelectedItem as Priority;
                Type type = ComboBox_Type.SelectedItem as Type;
                User responsible = ComboBox_Responsible.SelectedItem as User;
                DateTime? startedDate = RadDatePicker_StartDate.SelectedDate;
                DateTime? endDate = RadDatePicker_EndDate.SelectedDate;
                DateTime? estimatedEnd = TRadDatePicker_EstimatedEnd.SelectedDate;
                String name = TextBox_name.Text;

                Decimal? estimatedHours = null;
                if (TextBox_EstimatedHours.Text.Trim().Length > 0)
                    estimatedHours = Decimal.Parse(TextBox_EstimatedHours.Text);

                Decimal? timeUsed = null;
                if (TextBox_TimeUsed.Text.Trim().Length > 0)
                    timeUsed = Decimal.Parse(TextBox_TimeUsed.Text);

                DateTime? deadLine = RadDatePicker_Deadline.SelectedDate;
                Task parent = ComboBox_Parent.SelectedItem as Task;
                Subproject subproject = ComboBox_Subproject.SelectedItem as Subproject;
                //PROGRESS

                task.name = name;
                task.priority = priority;
                task.type = type;
                task.responsible = responsible;
                task.startedDate = startedDate;
                task.endDate = endDate;
                task.plannedEndDate = estimatedEnd;

                if (task.estimatedTime == null)
                    task.estimatedTime = estimatedHours;
                else
                    if (estimatedHours != task.estimatedTime)
                        task.addedEstimatedHours = task.estimatedTime - estimatedHours;

                task.timeUsed = timeUsed;
                task.deadline = deadLine;
                task.parent = parent;
                task.description = descriptionTextBox.Text;

                task = StatusPlanData.statusPlanHandler.saveTask(task, projectGroup, project, subproject);
                if (isNew)
                {
                    rp.IsHidden = true;
                    StatusPlanData.mainWindow.showTask(task, project, projectGroup, subproject);
                }
                else
                {
                    refreshFrame();
                }
            }
        }

        private void taskGridView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            RadGridView rgv = sender as RadGridView;
            Task t = null;
            if(rgv != null)
                t = rgv.SelectedItem as Task;
                if(t != null)
                    StatusPlanData.mainWindow.showTask(t,project,projectGroup,subproject);
        }
    }
}
